import { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { Box, Snackbar, Alert } from '@mui/material';
import dayjs from 'dayjs';

import Breadcrumb, { BreadcrumbItem } from '../../components/Breadcrumb';

import './StudentDetail.css';

// 引入API和类型
import {
    getStudentBaseInfo,
    updateStudentBaseInfo,
    importStudentBaseInfo,
    importStudentActivityInfo,
    importStudentInternshipInfo,
    getStudentBackgroundInfo,
    updateStudentBackgroundInfo,
    getStudentActivityInfo,
    updateStudentActivityInfo,
    createStudentActivityInfo,
    deleteStudentActivityInfo,
    getStudentInternshipInfo,
    updateStudentInternshipInfo,
    createStudentInternshipInfo,
    deleteStudentInternshipInfo,
    getStudentOfferInfo,
    getStudentOfferDetail,
    deleteStudentOfferInfo,
    updateStudentOfferInfo,
    createStudentOfferInfo,
    getStudentKeyInfo,
    updateStudentKeyInfo,
    getSpecialAttentionTypes,
    getParentsContactedOptions,
    getProvinceSystemReportOptions,
    getGraduateRegisteReportOptions,
    getStudentGraduateInfo,
    updateStudentGraduateInfo,
    getStudentDailyInfo,
    addStudentDailyInfo,
    deleteStudentDailyInfo,
    updateStudentDailyInfo,
    getGraduatePlanOptions,
    getOfferStatusOptions,
    getOfferTypeOptions,
    getDifficultyTypeOptions,
    getRecordTypeOptions,
    getEnrollmentStatusOptions,
    getEnrollmentTypeOptions,
    getAdvisorOptions
} from '../../api';
import {
    StudentBaseInfo,
    UpdateStudentBaseInfoParams,
    StudentBackgroundInfo,
    UpdateStudentBackgroundInfoParams,
    StudentActivityInfo,
    UpdateStudentActivityInfoParams,
    CreateStudentActivityInfoParams,
    DeleteStudentActivityInfoParams,
    StudentInternshipInfo,
    UpdateStudentInternshipInfoParams,
    CreateStudentInternshipInfoParams,
    DeleteStudentInternshipInfoParams,
    StudentOfferInfo,
    DeleteStudentOfferInfoParams,
    UpdateStudentOfferInfoParams,
    StudentKeyInfo,
    UpdateStudentKeyInfoParams,
    StudentGraduateInfo,
    UpdateStudentGraduateInfoParams,
    StudentDailyInfo,
    AddStudentDailyInfoParams,
    DeleteStudentDailyInfoParams,
    UpdateStudentDailyInfoParams
} from '../../api/types';
import { BasicInfo, BackgroundInfo, WorkExperience, KeyInfo, GraduationInfo, Log } from './types';

// 引入组件
import BasicInfoSection from './components/BasicInfoSection';
import BackgroundInfoSection from './components/BackgroundInfoSection';
import ActivitiesSection from './components/ActivitiesSection';
import InternshipsSection from './components/InternshipsSection';
import WorkExperienceSection from './components/WorkExperienceSection';
import KeyInfoSection from './components/KeyInfoSection';
import DailyInfoSection from './components/DailyInfoSection';
import EditDialog, { Field } from './components/EditDialog';
import ActivityDetailDialog from './components/ActivityDetailDialog';
import InternshipDetailDialog from './components/InternshipDetailDialog';
import WorkExperienceDetailDialog from './components/WorkExperienceDetailDialog';
import AddWorkExperienceDialog from './components/AddWorkExperienceDialog';
import ConfirmDialog from '../../components/ConfirmDialog';
import { Activity, Internship } from './components/types';

// 基本信息数据转换
const mapApiToBasicInfo = (apiData: StudentBaseInfo): BasicInfo => {
    // 处理预毕业学期时间戳
    let graduationPreYear = 'N/A';
    if (apiData.graduation_pre_year) {
        // 如果是时间戳格式（秒级）
        if (!isNaN(Number(apiData.graduation_pre_year))) {
            apiData.graduation_pre_year = apiData.graduation_pre_year.toString().padEnd(10, '0');
            const timestamp = Number(apiData.graduation_pre_year) * 1000;
            graduationPreYear = dayjs(timestamp).format('YYYY');
        } else {
            graduationPreYear = apiData.graduation_pre_year;
        }
    }

    return {
        base_info_id: apiData.base_info_id || '',
        studentId: apiData.sid,
        name: apiData.name,
        major: apiData.major || 'N/A',
        grade: apiData.grade || 'N/A',
        phone: apiData.phone || 'N/A',
        email: apiData.email || 'N/A',
        warnInfo: apiData.warn_info || 'N/A',
        gender: apiData.gender || 'N/A',
        academy: apiData.academy || 'N/A',
        cgpa: apiData.cgpa || 'N/A',
        status: apiData.status || 'N/A',
        enrollmentType: apiData.enrollment_type || 'N/A',
        creditStatus: apiData.credit_status || 'N/A',
        advisor: apiData.advisor || 'N/A',
        graduationPreTerm: apiData.graduation_pre_term,
        graduationPreYear
    };
};

// 背景信息数据转换
const mapApiToBackgroundInfo = (apiData: StudentBackgroundInfo): BackgroundInfo => {
    return {
        backgroundInfoId: apiData.background_info_id || 'N/A',
        resumeLevel:
            Array.isArray(apiData.resume_id) && apiData.resume_id.length > 0 ? apiData.resume_id[0].toString() : 'N/A',
        graduatePlan: apiData.graduate_plan || 'N/A',
        intendEmploymentArea: apiData.intend_employment_area || 'N/A',
        intendEmploymentIndustry: apiData.intend_employment_industry || 'N/A',
        intendEmploymentPosition: apiData.intend_employment_position || 'N/A',
        intendStudyArea: apiData.intend_study_area || 'N/A',
        intendStudySchool: apiData.intend_study_school || 'N/A',
        intendStudyMajor: apiData.intend_study_major || 'N/A',
        greGmat: apiData.gre_gmat || 'N/A',
        ieltsToefl: apiData.ielts_toefl || 'N/A',
        internshipCount: apiData.internship_count || '0',
        consultCount: apiData.consult_count || '0',
        activityCount: apiData.activity_count || '0'
    };
};

// 活动信息数据转换
const mapApiToActivityInfo = (apiData: StudentActivityInfo): Activity => {
    let date = '';
    if (apiData.activity_time) {
        apiData.activity_time = apiData.activity_time.toString().padEnd(10, '0');
        const timestamp = Number(apiData.activity_time) * 1000;
        date = dayjs(timestamp).format('YYYY-MM-DD');
    }

    return {
        id: Number(apiData.activity_info_id),
        date: date || apiData.activity_time,
        type: apiData.activity_type,
        name: apiData.activity_name,
        remark: apiData.remark
    };
};

// 实习信息数据转换
const mapApiToInternshipInfo = (apiData: StudentInternshipInfo): Internship => {
    return {
        id: Number(apiData.internship_info_id), // 将字符串ID转换为数字
        startDate: apiData.start_time,
        endDate: apiData.end_time,
        company: apiData.internship_company,
        position: apiData.internship_position,
        department: apiData.internship_location // 将实习地点作为部门显示
    };
};

// 工作信息数据转换
const mapApiToOfferInfo = (apiData: StudentOfferInfo): WorkExperience => {
    return {
        id: Number(apiData.offer_info_id), // 将字符串ID转换为数字
        offerType: apiData.offer_type,
        companyCollegeName: apiData.company_college_name,
        positionProjectName: apiData.position_project_name,
        industryName: apiData.industry_name,
        location: apiData.offer_area, // 将offer_area映射到location
        salaryMonth: apiData.salary_month,
        salaryYear: apiData.salary_year,
        acceptStatus: apiData.accept_status,
        remark: apiData.remark
    };
};

// 关键信息数据转换
const mapApiToKeyInfo = (apiData: StudentKeyInfo): KeyInfo => {
    return {
        specialAttention: apiData.apecial_attention || '--',
        difficultyType: apiData.difficulty_type || '--',
        supportNeed: apiData.support_need || '--',
        supportInfo: apiData.support_info || '--',
        parentsContacted: apiData.parents_contacted || '--',
        key_info_id: apiData.key_info_id || '--'
    };
};

// 毕业信息数据转换
const mapApiToGraduateInfo = (apiData: StudentGraduateInfo): GraduationInfo => {
    return {
        graduateInfoId: apiData.graduate_info_id || '--',
        provinceSystemReport: apiData.province_system_report || '--',
        graduateRegisteReport: apiData.graduate_registe_report || '--'
    };
};

// CDC记录数据转换
const mapApiToDailyInfo = (apiData: StudentDailyInfo): Log => {
    // 将时间戳转换为日期格式
    const timestamp = parseFloat(apiData.daily_record_time);
    if (!isNaN(timestamp)) {
        const date = new Date(timestamp * 1000);

        // 格式化为 YYYY-MM-DD HH:MM:SS
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        return {
            id: Number(apiData.daily_info_id), // 将字符串ID转换为数字
            recordOwner: apiData.daily_record_owner,
            recordType: apiData.daily_record_type,
            time: formattedDate,
            content: apiData.daily_record_detail
        };
    } else {
        return {
            id: parseInt(apiData.daily_info_id) || 0,
            recordOwner: apiData.daily_record_owner || '--',
            recordType: apiData.daily_record_type || '--',
            time: apiData.daily_record_time || '--',
            content: apiData.daily_record_detail || '--'
        };
    }
};

// 基础信息编辑字段
const getBasicInfoFields = (
    enrollmentStatusOptions: any,
    enrollmentTypeOptions: any,
    advisorOptions: any,
) : Field[] => [
    { name: 'studentId', label: '学号', type: 'text', required: true, disabled: true },
    { name: 'name', label: '姓名', type: 'text' },
    { name: 'gender', label: '性别', type: 'text' },
    { name: 'academy', label: '书院', type: 'text' },
    { name: 'major', label: '专业', type: 'text' },
    { name: 'grade', label: '年级', type: 'text' },
    { name: 'graduationPreTerm', label: '预毕业学期', type: 'text' },
    { name: 'graduationPreYear', label: '预毕业年份', type: 'year-picker' },
    { name: 'phone', label: '联系方式', type: 'text' },
    { name: 'email', label: '邮箱', type: 'text' },
    {
        name: 'status',
        label: '学籍状态',
        type: 'select',
        options:
            enrollmentStatusOptions.length > 0
                ? enrollmentStatusOptions.map((status) => ({ value: status, label: status }))
                : [
                      { value: '课程中有效', label: '课程中有效' },
                      { value: '休假', label: '休假' }
                ]
    },
    { name: 'cgpa', label: 'CGPA', type: 'text' },
    { name: 'creditStatus', label: '修分情况', type: 'text' },
    {
        name: 'enrollmentType',
        label: '招生类型',
        type: 'select',
        options:
            enrollmentTypeOptions.length > 0
                ? enrollmentTypeOptions.map((type) => ({ value: type, label: type }))
                : [
                      { value: '高考学生（中国籍）', label: '高考学生（中国籍）' },
                      { value: '海本学生（中国籍）', label: '海本学生（中国籍）' },
                      { value: '国际生', label: '国际生' }
                ]
    },
    { name: 'warnInfo', label: '预警信息', type: 'text' },
    {
        name: 'advisor',
        label: '顾问',
        type: 'select',
        options:
            advisorOptions.length > 0
                ? advisorOptions.map((advisor) => ({ value: advisor, label: advisor }))
                : [
                      { value: 'Maxine', label: 'Maxine' },
                      { value: 'Laila', label: 'Laila' },
                      { value: 'Zoey', label: 'Zoey' },
                      { value: 'Bella', label: 'Bella' },
                      { value: 'Mandy', label: 'Mandy' },
                      { value: 'Sherry', label: 'Sherry' },
                      { value: 'Ann', label: 'Ann' },
                      { value: 'Ashley', label: 'Ashley' }
                ]
    }
];

// 背景信息编辑字段
const getBackgroundInfoFields = (graduatePlanOptions: string[]): Field[] => {
    return [
        // { name: 'backgroundInfoId', label: '背景信息ID', type: 'text', disabled: true },
        // { name: 'resumeLevel', label: '简历', type: 'text' },
        {
            name: 'graduatePlan',
            label: '毕业计划',
            type: 'select',
            options:
                graduatePlanOptions.length > 0
                    ? graduatePlanOptions.map((plan) => ({ value: plan, label: plan }))
                    : [
                          { value: '境外升学', label: '境外升学' },
                          { value: '就业', label: '就业' },
                          { value: '优先境外升学', label: '优先境外升学' },
                          { value: '优先就业', label: '优先就业' },
                          { value: '创业', label: '创业' },
                          { value: '考公', label: '考公' },
                          { value: '国内考研', label: '国内考研' },
                          { value: '还不明确', label: '还不明确' }
                      ]
        },
        { name: 'internshipCount', label: '实习次数', type: 'text', disabled: true },
        { name: 'consultCount', label: '咨询次数', type: 'text', disabled: true },
        { name: 'activityCount', label: '活动次数', type: 'text', disabled: true },
        { name: 'greGmat', label: 'GRE/GMAT成绩', type: 'text' },
        { name: 'ieltsToefl', label: 'IELTS/TOEFL成绩', type: 'text' },
        { name: 'intendEmploymentArea', label: '意向就业地区', type: 'text' },
        { name: 'intendEmploymentIndustry', label: '意向就业行业', type: 'text' },
        { name: 'intendEmploymentPosition', label: '意向就业岗位', type: 'text' },
        { name: 'intendStudyArea', label: '意向升学地区', type: 'text' },
        { name: 'intendStudySchool', label: '意向升学院校', type: 'text' },
        { name: 'intendStudyMajor', label: '意向升学领域', type: 'text' }
    ];
};

// 活动信息编辑字段
const activityEditFields: Field[] = [
    // { name: 'id', label: '活动ID', type: 'text', disabled: true },
    { name: 'date', label: '活动时间', type: 'date', required: true },
    { name: 'type', label: '活动类型', type: 'text', required: true },
    { name: 'name', label: '活动名称', type: 'text', required: true },
    { name: 'remark', label: '备注', type: 'text' }
];

// 活动信息新增字段
const activityAddFields: Field[] = [
    { name: 'date', label: '活动时间', type: 'date', required: true },
    { name: 'type', label: '活动类型', type: 'text', required: true },
    { name: 'name', label: '活动名称', type: 'text', required: true },
    { name: 'remark', label: '备注', type: 'text' }
];

// 实习信息编辑字段
const internshipEditFields: Field[] = [
    // { name: 'id', label: '实习ID', type: 'text', disabled: true },
    { name: 'startDate', label: '开始时间', type: 'month-picker', required: true },
    { name: 'endDate', label: '结束时间', type: 'month-picker', required: true },
    { name: 'company', label: '实习公司', type: 'text', required: true },
    { name: 'position', label: '实习岗位', type: 'text', required: true },
    { name: 'department', label: '实习地点', type: 'text', required: true }
];

// 实习信息新增字段
const internshipAddFields: Field[] = [
    { name: 'startDate', label: '开始时间', type: 'month-picker', required: true },
    { name: 'endDate', label: '结束时间', type: 'month-picker', required: true },
    { name: 'company', label: '实习公司', type: 'text', required: true },
    { name: 'position', label: '实习岗位', type: 'text', required: true },
    { name: 'department', label: '实习地点', type: 'text', required: true }
];

// 工作信息编辑字段
const getWorkExperienceEditFields = (
    offerTypeOptions: string[],
    offerStatusOptions: string[],
    offerType?: string
): Field[] => {
    // 通用字段（无论是升学还是就业都需要的字段）
    const commonFields: Field[] = [
        { name: 'id', label: 'ID', type: 'hidden', disabled: true },
        {
            name: 'offerType',
            label: '类型',
            type: 'select',
            required: true,
            options:
                offerTypeOptions.length > 0
                    ? offerTypeOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '升学', label: '升学' },
                          { value: '就业', label: '就业' }
                      ]
        },
        { name: 'companyCollegeName', label: '企业/学校', type: 'school-autocomplete', required: true },
        { name: 'positionProjectName', label: '职位/项目', type: 'program-autocomplete', required: true },
        {
            name: 'location',
            label: '地点',
            type: 'autocomplete',
            required: true,
            apiEndpoint: '/b/sme/cdc/career/detail/offer_info/area/fuzzy'
        },
        {
            name: 'acceptStatus',
            label: '接受情况',
            type: 'select',
            required: true,
            options:
                offerStatusOptions.length > 0
                    ? offerStatusOptions.map((status) => ({ value: status, label: status }))
                    : [
                          { value: '接受', label: '接受' },
                          { value: '考虑中', label: '考虑中' },
                          { value: '放弃', label: '放弃' },
                          { value: '过期', label: '过期' }
                      ]
        },
        { name: 'remark', label: '备注', type: 'textarea' }
    ];

    // 根据offer类型返回不同的字段列表
    if (offerType === '就业' || !offerType) {
        // 就业特有字段
        const employmentFields: Field[] = [
            { name: 'salaryMonth', label: '月薪', type: 'text' },
            { name: 'salaryYear', label: '年薪', type: 'text' }
        ];

        // 将就业特有字段插入到地点和接受情况之间
        const insertIndex = commonFields.findIndex((field) => field.name === 'acceptStatus');
        if (insertIndex !== -1) {
            return [...commonFields.slice(0, insertIndex), ...employmentFields, ...commonFields.slice(insertIndex)];
        }
    } else if (offerType === '升学') {
        // 升学特有字段
        const educationFields: Field[] = [{ name: 'projectType', label: '项目类型', type: 'text', required: true }];

        // 将升学特有字段插入到地点和接受情况之间
        const insertIndex = commonFields.findIndex((field) => field.name === 'acceptStatus');
        if (insertIndex !== -1) {
            return [...commonFields.slice(0, insertIndex), ...educationFields, ...commonFields.slice(insertIndex)];
        }
    }

    // 默认返回通用字段
    return commonFields;
};

// 关键信息编辑字段（包含毕业信息）
const getKeyInfoEditFields = (
    specialAttentionOptions: any,
    parentsContactedOptions: any,
    difficultyTypeOptions: any,
    provinceSystemReportOptions: any,
    graduateRegisteReportOptions: any,
    includeGraduationInfo: boolean = true
): Field[] => {
    // 确保 specialAttentionOptions 是数组
    const specialOptions = Array.isArray(specialAttentionOptions) ? specialAttentionOptions : [];
    // 确保 parentsContactedOptions 是数组
    const parentsOptions = Array.isArray(parentsContactedOptions) ? parentsContactedOptions : [];
    // 确保 difficultyTypeOptions 是数组
    const difficultyOptions = Array.isArray(difficultyTypeOptions) ? difficultyTypeOptions : [];
    // 确保 provinceSystemReportOptions 是数组
    const provinceOptions = Array.isArray(provinceSystemReportOptions) ? provinceSystemReportOptions : [];
    // 确保 graduateRegisteReportOptions 是数组
    const graduateOptions = Array.isArray(graduateRegisteReportOptions) ? graduateRegisteReportOptions : [];

    // 基本的关键信息字段
    const keyInfoFields: Field[] = [
        // { name: 'key_info_id', label: '关键信息ID', type: 'text', disabled: true },
        {
            name: 'specialAttention',
            label: '特需生',
            type: 'select',
            required: true,
            options:
                specialOptions.length > 0
                    ? specialOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '是', label: '是' },
                          { value: '否', label: '否' }
                      ]
        },
        {
            name: 'difficultyType',
            label: '困难类型',
            type: 'select',
            required: true,
            options:
                difficultyOptions.length > 0
                    ? difficultyOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '普通', label: '普通' },
                          { value: '一般', label: '一般' }
                      ]
        },
        {
            name: 'supportNeed',
            label: '跨部门支持',
            type: 'select',
            required: true,
            options: [
                { value: '需CPDO 支持', label: '需CPDO 支持' },
                { value: '需书院支持', label: '需书院支持' },
                { value: '需领域教授支持', label: '需领域教授支持' },
                { value: '需学术导师支持', label: '需学术导师支持' }
            ]
        },
        { name: 'supportInfo', label: '支持内容', type: 'textarea' },
        {
            name: 'parentsContacted',
            label: '联系家长',
            type: 'select',
            required: true,
            options:
                parentsOptions.length > 0
                    ? parentsOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '是', label: '是' },
                          { value: '否', label: '否' }
                      ]
        }
    ];

    // 如果需要包含毕业信息字段
    if (includeGraduationInfo) {
        // 毕业信息字段
        const graduationFields: Field[] = [
            // { name: 'graduate_info_id', label: '毕业信息ID', type: 'text', disabled: true },
            {
                name: 'provinceSystemReport',
                label: '省厅系统填报',
                type: 'select',
                required: true,
                options:
                    provinceOptions.length > 0
                        ? provinceOptions.map((type) => ({ value: type, label: type }))
                        : [
                              { value: '已填报', label: '已填报' },
                              { value: '未填报', label: '未填报' }
                          ]
            },
            {
                name: 'graduateRegisteReport',
                label: '毕业生登记表填报',
                type: 'select',
                required: true,
                options:
                    graduateOptions.length > 0
                        ? graduateOptions.map((type) => ({ value: type, label: type }))
                        : [
                              { value: '已填报', label: '已填报' },
                              { value: '未填报', label: '未填报' }
                          ]
            }
        ];

        // 合并关键信息和毕业信息字段
        return [...keyInfoFields, ...graduationFields];
    }

    return keyInfoFields;
};

// 毕业信息编辑字段
const getGraduateInfoEditFields = (provinceSystemReportOptions: any, graduateRegisteReportOptions: any): Field[] => {
    // 确保 provinceSystemReportOptions 是数组
    const provinceOptions = Array.isArray(provinceSystemReportOptions) ? provinceSystemReportOptions : [];
    // 确保 graduateRegisteReportOptions 是数组
    const graduateOptions = Array.isArray(graduateRegisteReportOptions) ? graduateRegisteReportOptions : [];

    return [
        // { name: 'graduate_info_id', label: '毕业信息ID', type: 'text', disabled: true },
        {
            name: 'provinceSystemReport',
            label: '省厅系统填报',
            type: 'select',
            required: true,
            options:
                provinceOptions.length > 0
                    ? provinceOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '已填报', label: '已填报' },
                          { value: '未填报', label: '未填报' }
                      ]
        },
        {
            name: 'graduateRegisteReport',
            label: '毕业生登记表填报',
            type: 'select',
            required: true,
            options:
                graduateOptions.length > 0
                    ? graduateOptions.map((type) => ({ value: type, label: type }))
                    : [
                          { value: '已填报', label: '已填报' },
                          { value: '未填报', label: '未填报' }
                      ]
        }
    ];
};

// CDC记录添加字段
const getDailyInfoAddFields = (recordTypeOptions: any) : Field[] => [
    { name: 'daily_record_owner', label: '记录人', type: 'text', required: true, disabled: true },
    {
        name: 'record_type',
        label: '记录类型',
        type: 'select',
        required: true,
        options:
            recordTypeOptions.length > 0
                ? recordTypeOptions.map((type) => ({ value: type, label: type }))
                : [
                      { value: '1v1咨询', label: '1v1咨询' },
                      { value: '随访', label: '随访' },
                      { value: '其他约谈', label: '其他约谈' },
                      { value: '问卷信息', label: '问卷信息' },
                      { value: '邮件', label: '邮件' },
                      { value: '微信', label: '微信' }
                  ]
    },
    { name: 'record_time', label: '记录时间', type: 'date', required: true },
    { name: 'record_detail', label: '记录内容', type: 'textarea', required: true }
];

// CDC记录编辑字段
const getDailyInfoEditFields = (recordTypeOptions: any) : Field[] => [
    { name: 'daily_info_id', label: 'CDC记录ID', type: 'hidden', required: true },
    { name: 'daily_record_owner', label: '记录人', type: 'text', required: true, disabled: true },
    {
        name: 'record_type',
        label: '记录类型',
        type: 'select',
        required: true,
        options:
            recordTypeOptions.length > 0
                ? recordTypeOptions.map((type) => ({ value: type, label: type }))
                : [
                    { value: '1v1咨询', label: '1v1咨询' },
                    { value: '随访', label: '随访' },
                    { value: '其他约谈', label: '其他约谈' },
                    { value: '问卷信息', label: '问卷信息' },
                    { value: '邮件', label: '邮件' },
                    { value: '微信', label: '微信' }
                ]
    },
    { name: 'record_time', label: '记录时间', type: 'date', required: true },
    { name: 'record_detail', label: '记录内容', type: 'textarea', required: true }
];

const StudentDetail = () => {
    // 获取路由参数
    const { record_id, sid } = useParams<{ record_id: string; sid: string }>();

    // 获取页面信息
    useEffect(() => {
        fetchBasicInfo();
        fetchBackgroundInfo();
        fetchActivityInfo();
        fetchInternshipInfo();
        fetchOfferInfo();
        fetchKeyInfo(); // 获取关键信息`
        fetchGraduateInfo(); // 获取毕业信息
        fetchSpecialAttentionTypes(); // 获取特需生类型
        fetchDifficultyTypeOptions(); // 获取困难类型选项
        fetchParentsContactedOptions(); // 获取联系家长选项
        fetchProvinceSystemReportOptions(); // 获取省厅系统填报选项
        fetchGraduateRegisteReportOptions(); // 获取毕业生登记表填报选项
        fetchGraduatePlanOptions(); // 获取毕业计划选项
        // fetchChineseLevelOptions(); // 获取中文水平选项
        fetchOfferStatusOptions(); // 获取Offer状态选项
        fetchOfferTypeOptions(); // 获取Offer类型选项
        fetchDailyInfo();
        fetchRecordTypeOptions(); // 获取记录类型选项
        fetchEnrollmentStatusOptions(); // 获取学籍状态选项
        fetchEnrollmentTypeOptions(); // 获取学籍类型选项
        fetchAdvisorOptions(); // 获取顾问选项
    }, [record_id, sid]);

    // 加载状态
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);

    // 使用分离的数据模型
    const [basicInfo, setBasicInfo] = useState<BasicInfo | null>(null);
    const [backgroundInfo, setBackgroundInfo] = useState<BackgroundInfo | null>(null);
    const [backgroundLoading, setBackgroundLoading] = useState<boolean>(false);
    const [backgroundError, setBackgroundError] = useState<string | null>(null);

    // 活动信息状态
    const [activities, setActivities] = useState<Activity[]>([]);
    const [activitiesLoading, setActivitiesLoading] = useState<boolean>(false);
    const [activitiesError, setActivitiesError] = useState<string | null>(null);
    const [activitiesTotal, setActivitiesTotal] = useState<number>(0);

    // 实习信息状态
    const [internships, setInternships] = useState<Internship[]>([]);
    const [internshipsLoading, setInternshipsLoading] = useState<boolean>(false);
    const [internshipsError, setInternshipsError] = useState<string | null>(null);
    const [internshipsTotal, setInternshipsTotal] = useState<number>(0);

    // 工作信息状态
    const [workExperience, setWorkExperience] = useState<WorkExperience[]>([]);
    const [workExperienceLoading, setWorkExperienceLoading] = useState<boolean>(false);
    const [workExperienceError, setWorkExperienceError] = useState<string | null>(null);
    const [workExperienceTotal, setWorkExperienceTotal] = useState<number>(0);

    // 关键信息状态
    const [keyInfo, setKeyInfo] = useState<KeyInfo | null>(null);
    const [keyInfoLoading, setKeyInfoLoading] = useState<boolean>(false);
    const [keyInfoError, setKeyInfoError] = useState<string | null>(null);

    // 特需生类型状态
    const [specialAttentionTypes, setSpecialAttentionTypes] = useState<string[]>([]);

    // 困难类型选项状态
    const [difficultyTypeOptions, setDifficultyTypeOptions] = useState<string[]>([]);

    // 记录类型选项状态
    const [recordTypeOptions, setRecordTypeOptions] = useState<string[]>([]);

    // 学籍状态选项状态
    const [enrollmentStatusOptions, setEnrollmentStatusOptions] = useState<string[]>([]);

    // 招生类型选项状态
    const [enrollmentTypeOptions, setEnrollmentTypeOptions] = useState<string[]>([]);

    // 顾问选项状态
    const [advisorOptions, setAdvisorOptions] = useState<string[]>([]);

    // 联系家长选项状态
    const [parentsContactedOptions, setParentsContactedOptions] = useState<string[]>([]);

    // 省厅系统填报选项状态
    const [provinceSystemReportOptions, setProvinceSystemReportOptions] = useState<string[]>([]);

    // 毕业生登记表填报选项状态
    const [graduateRegisteReportOptions, setGraduateRegisteReportOptions] = useState<string[]>([]);

    // 毕业计划选项状态
    const [graduatePlanOptions, setGraduatePlanOptions] = useState<string[]>([]);

    // 中文水平选项状态
    // const [chineseLevelOptions, setChineseLevelOptions] = useState<string[]>([]);

    // Offer状态选项状态
    const [offerStatusOptions, setOfferStatusOptions] = useState<string[]>([]);

    // Offer类型选项状态
    const [offerTypeOptions, setOfferTypeOptions] = useState<string[]>([]);

    // 毕业信息状态
    const [graduationInfo, setGraduationInfo] = useState<GraduationInfo | null>(null);
    const [graduationInfoLoading, setGraduationInfoLoading] = useState<boolean>(false);
    const [graduationInfoError, setGraduationInfoError] = useState<string | null>(null);

    // CDC记录状态
    const [dailyInfo, setDailyInfo] = useState<Log[]>([]);
    const [dailyInfoLoading, setDailyInfoLoading] = useState<boolean>(false);
    const [dailyInfoError, setDailyInfoError] = useState<string | null>(null);
    const [dailyInfoTotal, setDailyInfoTotal] = useState<number>(0);

    // 分页状态
    const [page, setPage] = useState(1);
    const [rowsPerPage] = useState(5);

    // 对话框状态
    const [dialogOpen, setDialogOpen] = useState(false);
    const [dialogTitle, setDialogTitle] = useState('');
    const [dialogData, setDialogData] = useState<Record<string, any> | null>(null);
    const [dialogFields, setDialogFields] = useState<Field[]>([]);
    const [currentSection, setCurrentSection] = useState('');
    const [currentOfferType, setCurrentOfferType] = useState<string>('');

    // Snackbar状态
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

    // 活动详情对话框状态
    const [activityDetailOpen, setActivityDetailOpen] = useState(false);
    const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);

    // 实习详情对话框状态
    const [internshipDetailOpen, setInternshipDetailOpen] = useState(false);
    const [selectedInternship, setSelectedInternship] = useState<Internship | null>(null);

    // 工作信息详情对话框状态
    const [workExperienceDetailOpen, setWorkExperienceDetailOpen] = useState(false);
    const [selectedWorkExperience, setSelectedWorkExperience] = useState<WorkExperience | null>(null);

    // 工作信息添加对话框状态
    const [addWorkExperienceOpen, setAddWorkExperienceOpen] = useState(false);

    // 导入状态
    const [importLoading, setImportLoading] = useState(false);
    const baseInfoFileInputRef = useRef<HTMLInputElement>(null);
    const activityFileInputRef = useRef<HTMLInputElement>(null);
    const internshipFileInputRef = useRef<HTMLInputElement>(null);

    // 确认对话框状态
    const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
    const [confirmDialogTitle, setConfirmDialogTitle] = useState('');
    const [confirmDialogContent, setConfirmDialogContent] = useState('');
    const [confirmDialogAction, setConfirmDialogAction] = useState<() => () => Promise<void>>(
        () => () => Promise.resolve()
    );
    const [_, setDeleteActivityId] = useState<number | null>(null);

    // 获取记录类型选项
    const fetchRecordTypeOptions = async () => {
        try {
            // 获取记录类型选项列表
            const options = await getRecordTypeOptions();
            console.log('Record type options:', options);
            setRecordTypeOptions(options);
        } catch (error) {
            console.error('获取记录类型选项列表失败:', error);
            setRecordTypeOptions([]);
        }
    };

    // 获取学籍状态选项
    const fetchEnrollmentStatusOptions = async () => {
        try {
            // 获取学籍状态选项列表
            const options = await getEnrollmentStatusOptions();
            console.log('Enrollment status options:', options);
            setEnrollmentStatusOptions(options);
        } catch (error) {
            console.error('获取学籍状态选项列表失败:', error);
            setEnrollmentStatusOptions([]);
        }
    };

    // 获取招生类型选项
    const fetchEnrollmentTypeOptions = async () => {
        try {
            // 获取招生类型选项列表
            const options = await getEnrollmentTypeOptions();
            console.log('Enrollment type options:', options);
            setEnrollmentTypeOptions(options);
        } catch (error) {
            console.error('获取招生类型选项列表失败:', error);
            setEnrollmentTypeOptions([]);
        }
    };

    // 获取顾问选项
    const fetchAdvisorOptions = async () => {
        try {
            // 获取顾问选项列表
            const options = await getAdvisorOptions();
            console.log('Advisor options:', options);
            setAdvisorOptions(options);
        } catch (error) {
            console.error('获取顾问选项列表失败:', error);
            setAdvisorOptions([]);
        }
    };

    // 获取基础信息
    const fetchBackgroundInfo = async () => {
        if (!record_id || !sid) return;

        setBackgroundLoading(true);
        setBackgroundError(null);

        try {
            const response = await getStudentBackgroundInfo({
                record_id,
                sid
            });

            // 将API数据转换为展示所需的格式
            const formattedData = mapApiToBackgroundInfo(response);
            setBackgroundInfo(formattedData);
        } catch (error) {
            console.error('获取学生背景信息失败:', error);
            setBackgroundError('获取学生背景信息失败，请稍后重试');
        } finally {
            setBackgroundLoading(false);
        }
    };

    // 获取背景信息
    const fetchBasicInfo = async () => {
        if (!record_id || !sid) return;

        setLoading(true);
        setError(null);

        try {
            const response = await getStudentBaseInfo({
                record_id,
                sid
            });

            // 将API数据转换为展示所需的格式
            const formattedData = mapApiToBasicInfo(response);
            setBasicInfo(formattedData);
        } catch (error) {
            console.error('获取学生基础信息失败:', error);
            setError('获取学生信息失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 获取活动信息
    const fetchActivityInfo = async (page = '1') => {
        if (!record_id || !sid) return;

        setActivitiesLoading(true);
        setActivitiesError(null);

        try {
            const response = await getStudentActivityInfo({
                record_id,
                sid,
                page,
                limit: '5'
            });

            // 将API数据转换为展示所需的格式
            const formattedData = response.detail.map((item) => mapApiToActivityInfo(item));
            setActivities(formattedData);
            // 设置总数
            setActivitiesTotal(Number(response.total));
        } catch (error) {
            console.error('获取学生活动信息失败:', error);
            setActivitiesError('获取学生活动信息失败，请稍后重试');
        } finally {
            setActivitiesLoading(false);
        }
    };

    // 获取实习信息
    const fetchInternshipInfo = async (page = '1') => {
        if (!record_id || !sid) return;

        setInternshipsLoading(true);
        setInternshipsError(null);

        try {
            const response = await getStudentInternshipInfo({
                record_id,
                sid,
                page,
                limit: '5'
            });

            // 将API数据转换为展示所需的格式
            const formattedData = response.detail.map((item) => mapApiToInternshipInfo(item));
            setInternships(formattedData);
            setInternshipsTotal(Number(response.total));
        } catch (error) {
            console.error('获取学生实习信息失败:', error);
            setInternshipsError('获取学生实习信息失败，请稍后重试');
        } finally {
            setInternshipsLoading(false);
        }
    };

    // 获取工作信息
    const fetchOfferInfo = async (page = '1') => {
        if (!record_id || !sid) return;

        setWorkExperienceLoading(true);
        setWorkExperienceError(null);

        try {
            const response = await getStudentOfferInfo({
                record_id,
                sid,
                page,
                limit: '5'
            });

            // 将API数据转换为展示所需的格式
            const formattedData = response.detail.map((item) => mapApiToOfferInfo(item));
            setWorkExperience(formattedData);
            setWorkExperienceTotal(Number(response.total));
        } catch (error) {
            console.error('获取学生工作信息失败:', error);
            setWorkExperienceError('获取学生工作信息失败，请稍后重试');
        } finally {
            setWorkExperienceLoading(false);
        }
    };

    // 获取关键信息
    const fetchKeyInfo = async () => {
        if (!record_id || !sid) return;

        setKeyInfoLoading(true);
        setKeyInfoError(null);

        try {
            const response = await getStudentKeyInfo({ record_id, sid });

            // 将API数据转换为展示所需的格式
            const formattedData = mapApiToKeyInfo(response);
            setKeyInfo(formattedData);
        } catch (error) {
            console.error('获取学生关键信息失败:', error);
            setKeyInfoError('获取学生关键信息失败，请稍后重试');
        } finally {
            setKeyInfoLoading(false);
        }
    };

    // 获取特需生类型
    const fetchSpecialAttentionTypes: any = async () => {
        try {
            // 获取特需生类型列表，现在返回的是字符串数组
            const types = await getSpecialAttentionTypes();
            console.log('Special attention types:', types);
            setSpecialAttentionTypes(types);
        } catch (error) {
            console.error('获取特需生类型列表失败:', error);
            setSpecialAttentionTypes([]);
        }
    };

    // 获取困难类型选项
    const fetchDifficultyTypeOptions = async () => {
        try {
            // 获取困难类型选项列表
            const options = await getDifficultyTypeOptions();
            console.log('Difficulty type options:', options);
            setDifficultyTypeOptions(options);
        } catch (error) {
            console.error('获取困难类型选项列表失败:', error);
            setDifficultyTypeOptions([]);
        }
    };

    // 获取联系家长选项
    const fetchParentsContactedOptions = async () => {
        try {
            // 获取联系家长选项列表，现在返回的是字符串数组
            const options = await getParentsContactedOptions();
            console.log('Parents contacted options:', options);
            setParentsContactedOptions(options);
        } catch (error) {
            console.error('获取联系家长选项列表失败:', error);
            setParentsContactedOptions([]);
        }
    };

    // 获取省厅系统填报选项
    const fetchProvinceSystemReportOptions = async () => {
        try {
            // 获取省厅系统填报选项列表，现在返回的是字符串数组
            const options = await getProvinceSystemReportOptions();
            console.log('Province system report options:', options);
            setProvinceSystemReportOptions(options);
        } catch (error) {
            console.error('获取省厅系统填报选项列表失败:', error);
            setProvinceSystemReportOptions([]);
        }
    };

    // 获取毕业生登记表填报选项
    const fetchGraduateRegisteReportOptions = async () => {
        try {
            // 获取毕业生登记表填报选项列表，现在返回的是字符串数组
            const options = await getGraduateRegisteReportOptions();
            console.log('Graduate registe report options:', options);
            setGraduateRegisteReportOptions(options);
        } catch (error) {
            console.error('获取毕业生登记表填报选项列表失败:', error);
            setGraduateRegisteReportOptions([]);
        }
    };

    // 获取毕业计划选项
    const fetchGraduatePlanOptions = async () => {
        try {
            // 获取毕业计划选项列表
            const options = await getGraduatePlanOptions();
            console.log('Graduate plan options:', options);
            setGraduatePlanOptions(options);
        } catch (error) {
            console.error('获取毕业计划选项列表失败:', error);
            setGraduatePlanOptions([]);
        }
    };

    // 获取中文水平选项
    // const fetchChineseLevelOptions = async () => {
    //     try {
    //         // 获取中文水平选项列表
    //         const options = await getChineseLevelOptions();
    //         console.log('Chinese level options:', options);
    //         setChineseLevelOptions(options);
    //     } catch (error) {
    //         console.error('获取中文水平选项列表失败:', error);
    //         setChineseLevelOptions([]);
    //     }
    // };

    // 获取Offer状态选项
    const fetchOfferStatusOptions = async () => {
        try {
            // 获取Offer状态选项列表
            const options = await getOfferStatusOptions();
            console.log('Offer status options:', options);
            setOfferStatusOptions(options);
        } catch (error) {
            console.error('获取Offer状态选项列表失败:', error);
            setOfferStatusOptions([]);
        }
    };

    // 获取Offer类型选项
    const fetchOfferTypeOptions = async () => {
        try {
            // 获取Offer类型选项列表
            const options = await getOfferTypeOptions();
            console.log('Offer type options:', options);
            setOfferTypeOptions(options);
        } catch (error) {
            console.error('获取Offer类型选项列表失败:', error);
            setOfferTypeOptions([]);
        }
    };

    // 获取毕业信息
    const fetchGraduateInfo = async () => {
        if (!record_id || !sid) return;

        setGraduationInfoLoading(true);
        setGraduationInfoError(null);

        try {
            const response = await getStudentGraduateInfo({ record_id, sid });

            // 将API数据转换为展示所需的格式
            const formattedData = mapApiToGraduateInfo(response);
            setGraduationInfo(formattedData);
        } catch (error) {
            console.error('获取学生毕业信息失败:', error);
            setGraduationInfoError('获取学生毕业信息失败，请稍后重试');
        } finally {
            setGraduationInfoLoading(false);
        }
    };

    // 获取CDC记录
    const fetchDailyInfo = async (page = '1') => {
        if (!record_id || !sid) return;

        setDailyInfoLoading(true);
        setDailyInfoError(null);

        try {
            const response = await getStudentDailyInfo({
                record_id,
                sid,
                page,
                limit: '10'
            });

            // 将API数据转换为展示所需的格式
            const formattedData = response.detail.map((item) => mapApiToDailyInfo(item));
            setDailyInfo(formattedData);
            // 设置总数
            setDailyInfoTotal(Number(response.total));
        } catch (error) {
            console.error('获取学生CDC记录失败:', error);
            setDailyInfoError('获取学生CDC记录失败，请稍后重试');
        } finally {
            setDailyInfoLoading(false);
        }
    };

    // 处理基础信息导入
    const handleImportBaseInfo = () => {
        // 如果已经在导入中，不允许再次点击
        if (importLoading) return;

        // 触发文件选择框
        baseInfoFileInputRef.current?.click();
    };

    // 处理活动信息导入
    const handleImportActivityInfo = () => {
        // 如果已经在导入中，不允许再次点击
        if (importLoading) return;

        // 触发文件选择框
        activityFileInputRef.current?.click();
    };

    // 处理实习信息导入
    const handleImportInternshipInfo = () => {
        // 如果已经在导入中，不允许再次点击
        if (importLoading) return;

        // 触发文件选择框
        internshipFileInputRef.current?.click();
    };

    // 处理基础信息文件选择
    const handleBaseInfoFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];

        // 验证文件类型
        const fileExtension = file.name.split('.').pop()?.toLowerCase();
        if (fileExtension !== 'xlsx') {
            setSnackbarMessage('请选择Excel文件(.xlsx)');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
            return;
        }

        setImportLoading(true);

        try {
            // 使用封装好的API方法导入文件
            await importStudentBaseInfo(file);

            // 上传成功，重新获取基础信息
            await fetchBasicInfo();

            // 显示成功提示
            setSnackbarMessage('基础信息导入成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('基础信息导入失败:', error);
            setSnackbarMessage('基础信息导入失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setImportLoading(false);
            // 清空文件选择，以便可以再次选择同一个文件
            if (event.target) {
                event.target.value = '';
            }
        }
    };

    // 处理活动信息文件选择
    const handleActivityFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];

        // 验证文件类型
        const fileExtension = file.name.split('.').pop()?.toLowerCase();
        if (fileExtension !== 'xlsx') {
            setSnackbarMessage('请选择Excel文件(.xlsx)');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
            return;
        }

        setImportLoading(true);

        try {
            // 使用封装好的API方法导入文件
            await importStudentActivityInfo(file);

            // 上传成功，重新获取活动信息
            await fetchActivityInfo();

            // 显示成功提示
            setSnackbarMessage('活动信息导入成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('活动信息导入失败:', error);
            setSnackbarMessage('活动信息导入失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setImportLoading(false);
            // 清空文件选择，以便可以再次选择同一个文件
            if (event.target) {
                event.target.value = '';
            }
        }
    };

    // 处理实习信息文件选择
    const handleInternshipFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];

        // 验证文件类型
        const fileExtension = file.name.split('.').pop()?.toLowerCase();
        if (fileExtension !== 'xlsx') {
            setSnackbarMessage('请选择Excel文件(.xlsx)');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
            return;
        }

        setImportLoading(true);

        try {
            // 使用封装好的API方法导入文件
            await importStudentInternshipInfo(file);

            // 上传成功，重新获取实习信息
            await fetchInternshipInfo();

            // 显示成功提示
            setSnackbarMessage('实习信息导入成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('实习信息导入失败:', error);
            setSnackbarMessage('实习信息导入失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setImportLoading(false);
            // 清空文件选择，以便可以再次选择同一个文件
            if (event.target) {
                event.target.value = '';
            }
        }
    };

    // 面包屑导航配置
    const breadcrumbItems: BreadcrumbItem[] = [
        { title: '首页' },
        { title: '学生信息', href: '/student' },
        { title: '学生详情' }
    ];

    // 更新数据的通用处理函数
    const handleSaveData = async (updatedData: Record<string, any>) => {
        // 根据当前编辑的部分更新相应的数据
        switch (currentSection) {
            case '基础信息':
                try {
                    // 设置加载状态
                    setLoading(true);
                    setError(null);

                    // 处理预毕业学期日期，转为秒级时间戳
                    let graduationPreTimestamp = '';
                    if (updatedData.graduationPreYear) {
                        // 使用dayjs将日期字符串转换为时间戳
                        const date = dayjs(updatedData.graduationPreYear);
                        if (date.isValid()) {
                            graduationPreTimestamp = date.unix().toString(); // 转换为秒级时间戳
                        } else {
                            graduationPreTimestamp = updatedData.graduationPreYear;
                        }
                    }

                    // 准备请求参数
                    const params: UpdateStudentBaseInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        base_info_id: basicInfo?.base_info_id || '',
                        name: updatedData.name,
                        major: updatedData.major,
                        grade: updatedData.grade,
                        phone: updatedData.phone,
                        email: updatedData.email,
                        warn_info: updatedData.warnInfo,
                        gender: updatedData.gender,
                        academy: updatedData.academy,
                        cgpa: updatedData.cgpa,
                        status: updatedData.status,
                        enrollment_type: updatedData.enrollmentType,
                        credit_status: updatedData.creditStatus,
                        advisor: updatedData.advisor,
                        graduation_pre_term: updatedData.graduationPreTerm,
                        graduation_pre_year: graduationPreTimestamp
                    };

                    // 调用更新接口
                    await updateStudentBaseInfo(params);

                    // 更新成功后重新获取最新数据
                    await fetchBasicInfo();

                    // 显示成功提示
                    setSnackbarMessage('基础信息更新成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);
                } catch (error) {
                    console.error('更新基础信息失败:', error);
                    setError('更新基础信息失败，请稍后重试');
                    setSnackbarMessage('更新基础信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setLoading(false);
                }
                break;
            case '背景信息':
                try {
                    // 设置加载状态
                    setBackgroundLoading(true);
                    setBackgroundError(null);

                    // 准备请求参数
                    const params: UpdateStudentBackgroundInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        background_info_id: backgroundInfo?.backgroundInfoId || '',
                        // 如果简历ID是字符串数组，需要转换为数字数组
                        resume_id: Array.isArray(updatedData.resumeId)
                            ? updatedData.resumeId.map((id) => parseInt(id, 10)).filter((id) => !isNaN(id))
                            : [],
                        graduate_plan: updatedData.graduatePlan,
                        gre_gmat: updatedData.greGmat,
                        ielts_toefl: updatedData.ieltsToefl,
                        intend_employment_area: updatedData.intendEmploymentArea,
                        intend_employment_industry: updatedData.intendEmploymentIndustry,
                        intend_employment_position: updatedData.intendEmploymentPosition,
                        intend_study_area: updatedData.intendStudyArea,
                        intend_study_school: updatedData.intendStudySchool,
                        intend_study_major: updatedData.intendStudyMajor
                    };

                    // 调用更新接口
                    await updateStudentBackgroundInfo(params);

                    // 更新成功后重新获取最新数据
                    await fetchBackgroundInfo();

                    // 显示成功提示
                    setSnackbarMessage('背景信息更新成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);
                } catch (error) {
                    console.error('更新背景信息失败:', error);
                    setBackgroundError('更新背景信息失败，请稍后重试');
                    setSnackbarMessage('更新背景信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setBackgroundLoading(false);
                }
                break;
            case '活动信息':
                try {
                    // 设置加载状态
                    setActivitiesLoading(true);
                    setActivitiesError(null);

                    // 将日期转换为时间戳格式
                    const dateStr = updatedData.date;
                    let timestamp = '';

                    if (dateStr) {
                        // 将日期字符串转换为时间戳
                        const dateObj = new Date(dateStr);
                        timestamp = Math.floor(dateObj.getTime() / 1000).toString(); // 转换为秒级时间戳
                    }

                    // 判断是添加还是更新
                    if (updatedData.id) {
                        // 更新现有活动
                        const updateParams: UpdateStudentActivityInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            activity_info_id: updatedData.id.toString(),
                            activity_time: timestamp,
                            activity_type: updatedData.type,
                            activity_name: updatedData.name,
                            remark: updatedData.remark
                        };

                        // 调用更新接口
                        await updateStudentActivityInfo(updateParams);
                        console.log('更新活动信息:', updateParams);
                    } else {
                        // 添加新活动
                        const createParams: CreateStudentActivityInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            activity_time: timestamp,
                            activity_type: updatedData.type,
                            activity_name: updatedData.name,
                            remark: updatedData.remark
                        };

                        // 不需要传递活动ID，由服务器自动生成

                        // 调用创建接口
                        await createStudentActivityInfo(createParams);
                        console.log('创建活动信息:', createParams);
                    }

                    await fetchActivityInfo();

                    // 显示成功提示
                    setSnackbarMessage('活动信息保存成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                } catch (error) {
                    console.error('保存活动信息失败:', error);
                    setActivitiesError('保存活动信息失败，请稍后重试');
                    setSnackbarMessage('保存活动信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setActivitiesLoading(false);
                }
                break;
            case '实习信息':
                try {
                    // 设置加载状态
                    setInternshipsLoading(true);
                    setInternshipsError(null);

                    // 将开始时间转换为时间戳格式
                    const startDateStr = updatedData.startDate;
                    let startTimestamp = '';

                    if (startDateStr) {
                        // 将日期字符串转换为时间戳
                        const dateObj = new Date(startDateStr);
                        startTimestamp = Math.floor(dateObj.getTime() / 1000).toString(); // 转换为秒级时间戳
                    }

                    // 将结束时间转换为时间戳格式
                    const endDateStr = updatedData.endDate;
                    let endTimestamp = '';

                    if (endDateStr) {
                        // 将日期字符串转换为时间戳
                        const dateObj = new Date(endDateStr);
                        endTimestamp = Math.floor(dateObj.getTime() / 1000).toString(); // 转换为秒级时间戳
                    }

                    // 判断是添加还是更新
                    if (updatedData.id) {
                        // 更新现有实习
                        const updateParams: UpdateStudentInternshipInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            internship_info_id: updatedData.id.toString(),
                            start_time: startTimestamp,
                            end_time: endTimestamp,
                            internship_company: updatedData.company,
                            internship_position: updatedData.position,
                            internship_location: updatedData.department
                        };

                        // 调用更新接口
                        await updateStudentInternshipInfo(updateParams);
                        console.log('更新实习信息:', updateParams);
                    } else {
                        // 添加新实习
                        const createParams: CreateStudentInternshipInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            start_time: startTimestamp,
                            end_time: endTimestamp,
                            company: updatedData.company,
                            position: updatedData.position,
                            location: updatedData.department
                        };

                        // 调用创建接口
                        await createStudentInternshipInfo(createParams);
                        console.log('创建实习信息:', createParams);
                    }

                    // 重新获取实习信息
                    await fetchInternshipInfo();

                    // 显示成功提示
                    setSnackbarMessage('实习信息保存成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                } catch (error) {
                    console.error('保存实习信息失败:', error);
                    setInternshipsError('保存实习信息失败，请稍后重试');
                    setSnackbarMessage('保存实习信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setInternshipsLoading(false);
                }
                break;

            case 'Offer信息':
                try {
                    console.log(updatedData);

                    // 设置加载状态
                    setWorkExperienceLoading(true);
                    setWorkExperienceError(null);

                    // 准备请求参数
                    const params: UpdateStudentOfferInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        company_college_name: updatedData.companyCollegeName,
                        offer_info_id: updatedData.id.toString(),
                        offer_type: updatedData.offerType,
                        location: updatedData.location || '', // 使用location字段
                        position_project_name: updatedData.positionProjectName || '',
                        project_type: updatedData.projectType || '',
                        company_name: '', // 必要的空字段
                        position: '', // 必要的空字段
                        salary_month: updatedData.salaryMonth || '',
                        salary_year: updatedData.salaryYear || '',
                        accept_status: updatedData.acceptStatus,
                        remark: updatedData.remark || ''
                    };

                    // 调用更新接口
                    await updateStudentOfferInfo(params);

                    // 更新成功后重新获取工作信息列表
                    await fetchOfferInfo();

                    // 显示成功提示
                    setSnackbarMessage('工作信息更新成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                    // 清空选中的工作信息
                    setSelectedWorkExperience(null);
                } catch (error) {
                    console.error('保存工作信息失败:', error);
                    setWorkExperienceError('保存工作信息失败，请稍后重试');
                    setSnackbarMessage('保存工作信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setWorkExperienceLoading(false);
                }
                break;
            case '关键信息':
                try {
                    // 设置加载状态
                    setKeyInfoLoading(true);
                    setKeyInfoError(null);
                    setGraduationInfoLoading(true);
                    setGraduationInfoError(null);

                    // 准备关键信息请求参数
                    const keyInfoParams: UpdateStudentKeyInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        key_info_id: updatedData.key_info_id,
                        special_attention: updatedData.specialAttention,
                        difficulty_type: updatedData.difficultyType,
                        support_need: updatedData.supportNeed,
                        support_info: updatedData.supportInfo || '',
                        parents_contacted: updatedData.parentsContacted
                    };

                    // 准备毕业信息请求参数
                    const graduateInfoParams: UpdateStudentGraduateInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        graduate_info_id: updatedData.graduate_info_id || graduationInfo?.graduateInfoId || '',
                        province_system_report: updatedData.provinceSystemReport,
                        graduate_registe_report: updatedData.graduateRegisteReport
                    };

                    // 并行调用两个更新接口
                    await Promise.all([
                        updateStudentKeyInfo(keyInfoParams),
                        updateStudentGraduateInfo(graduateInfoParams)
                    ]);

                    // 更新成功后重新获取关键信息和毕业信息
                    await Promise.all([fetchKeyInfo(), fetchGraduateInfo()]);

                    // 显示成功提示
                    setSnackbarMessage('关键信息更新成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                } catch (error) {
                    console.error('保存关键信息失败:', error);
                    setKeyInfoError('保存关键信息失败，请稍后重试');
                    setGraduationInfoError('保存毕业信息失败，请稍后重试');
                    setSnackbarMessage('保存信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setKeyInfoLoading(false);
                    setGraduationInfoLoading(false);
                }
                break;
            case '毕业信息':
                try {
                    // 设置加载状态
                    setGraduationInfoLoading(true);
                    setGraduationInfoError(null);

                    // 准备请求参数
                    const params: UpdateStudentGraduateInfoParams = {
                        record_id: record_id || '',
                        sid: sid || '',
                        province_system_report: updatedData.provinceSystemReport,
                        graduate_registe_report: updatedData.graduateRegisteReport
                    };

                    // 调用更新接口ss
                    await updateStudentGraduateInfo({ ...params, graduate_info_id: graduationInfo?.graduateInfoId });

                    // 更新成功后重新获取毕业信息
                    await fetchGraduateInfo();

                    // 显示成功提示
                    setSnackbarMessage('毕业信息更新成功');
                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                } catch (error) {
                    console.error('保存毕业信息失败:', error);
                    setGraduationInfoError('保存毕业信息失败，请稍后重试');
                    setSnackbarMessage('保存毕业信息失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setGraduationInfoLoading(false);
                }
                break;
            case 'CDC记录':
                try {
                    // 设置加载状态
                    setDailyInfoLoading(true);
                    setDailyInfoError(null);

                    // 处理日期格式，转换为秒级时间戳
                    let recordTimeTimestamp = '';
                    if (updatedData.record_time) {
                        // 使用dayjs将日期字符串转换为时间戳
                        const date = dayjs(updatedData.record_time);
                        if (date.isValid()) {
                            recordTimeTimestamp = date.unix().toString(); // 转换为秒级时间戳
                        } else {
                            recordTimeTimestamp = updatedData.record_time;
                        }
                    }

                    // 判断是添加还是编辑
                    if (updatedData.daily_info_id) {
                        // 编辑CDC记录
                        const params: UpdateStudentDailyInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            daily_info_id: updatedData.daily_info_id,
                            record_name: updatedData.record_name,
                            record_type: updatedData.record_type,
                            record_time: recordTimeTimestamp,
                            record_detail: updatedData.record_detail
                        };

                        // 调用更新接口
                        await updateStudentDailyInfo(params);

                        // 显示成功提示
                        setSnackbarMessage('CDC记录更新成功');
                    } else {
                        // 添加CDC记录
                        const params: AddStudentDailyInfoParams = {
                            record_id: record_id || '',
                            sid: sid || '',
                            record_name: updatedData.record_name,
                            record_type: updatedData.record_type,
                            record_time: recordTimeTimestamp,
                            record_detail: updatedData.record_detail
                        };

                        // 调用添加接口
                        await addStudentDailyInfo(params);

                        // 显示成功提示
                        setSnackbarMessage('CDC记录添加成功');
                    }

                    // 操作成功后重新获取CDC记录
                    await fetchDailyInfo();

                    setSnackbarSeverity('success');
                    setSnackbarOpen(true);

                    // 关闭对话框
                    setDialogOpen(false);
                } catch (error) {
                    console.error('操作CDC记录失败:', error);
                    setDailyInfoError('操作CDC记录失败，请稍后重试');
                    setSnackbarMessage('操作CDC记录失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setDailyInfoLoading(false);
                }
                break;
            default:
                console.log(`${currentSection}的保存功能尚未实现`);
        }
    };

    // 关闭Snackbar
    const handleSnackbarClose = () => {
        setSnackbarOpen(false);
    };

    // 编辑按钮处理函数
    const handleEdit = (section: string) => {
        console.log(`编辑${section}部分`);
        setCurrentSection(section);

        switch (section) {
            case '基础信息':
                setDialogTitle('编辑基础信息');
                setDialogData(basicInfo);
                setDialogFields(getBasicInfoFields(enrollmentStatusOptions, enrollmentTypeOptions, advisorOptions));
                setDialogOpen(true);
                break;
            case '背景信息':
                setDialogTitle('编辑背景信息');
                setDialogData(backgroundInfo);
                setDialogFields(getBackgroundInfoFields(graduatePlanOptions));
                setDialogOpen(true);
                break;
            case '活动信息':
                setDialogTitle('编辑活动信息');
                setDialogData(null); // 这里应该是null，因为是空表单，用于添加新活动
                setDialogFields(activityAddFields); // 使用活动新增字段
                setDialogOpen(true);
                break;
            case '实习信息':
                setDialogTitle('编辑实习信息');
                setDialogData(null); // 这里应该是null，因为是空表单，用于添加新实习
                setDialogFields(internshipAddFields); // 使用实习新增字段
                setDialogOpen(true);
                break;
            case 'Offer信息':
                // 这里不再直接处理编辑逻辑，而是在WorkExperienceSection中处理
                console.log('请先选择要编辑的工作信息');
                setSnackbarMessage('请先选择要编辑的工作信息');
                setSnackbarSeverity('info');
                setSnackbarOpen(true);
                break;
            case '关键信息':
                if (keyInfo) {
                    setCurrentSection('关键信息');
                    setDialogTitle('编辑关键信息');

                    // 准备编辑数据，合并关键信息和毕业信息
                    const editData = {
                        ...keyInfo,
                        // 添加毕业信息字段
                        provinceSystemReport: graduationInfo?.provinceSystemReport || '',
                        graduateRegisteReport: graduationInfo?.graduateRegisteReport || '',
                        graduate_info_id: graduationInfo?.graduateInfoId || ''
                    };

                    setDialogData(editData);
                    setDialogFields(
                        getKeyInfoEditFields(
                            specialAttentionTypes,
                            parentsContactedOptions,
                            difficultyTypeOptions,
                            provinceSystemReportOptions,
                            graduateRegisteReportOptions,
                            true // 包含毕业信息字段
                        )
                    );
                    setDialogOpen(true);
                } else {
                    setSnackbarMessage('关键信息加载失败，请刷新页面后重试');
                    setSnackbarSeverity('warning');
                    setSnackbarOpen(true);
                }
                break;
            case '毕业信息':
                if (graduationInfo) {
                    setCurrentSection('毕业信息');
                    setDialogTitle('编辑毕业信息');

                    // 准备编辑数据
                    const editData = {
                        graduate_info_id: graduationInfo.graduateInfoId || '',
                        provinceSystemReport: graduationInfo.provinceSystemReport,
                        graduateRegisteReport: graduationInfo.graduateRegisteReport
                    };

                    setDialogData(editData);
                    setDialogFields(
                        getGraduateInfoEditFields(provinceSystemReportOptions, graduateRegisteReportOptions)
                    );
                    setDialogOpen(true);
                } else {
                    setSnackbarMessage('毕业信息加载失败，请刷新页面后重试');
                    setSnackbarSeverity('warning');
                    setSnackbarOpen(true);
                }
                break;
            default:
                console.log(`${section}的编辑功能尚未实现`);
        }
    };

    // 添加按钮处理函数
    const handleAdd = (section: string) => {
        console.log(`添加${section}信息`);

        if (section === '活动') {
            setCurrentSection('活动信息');
            setDialogTitle('添加活动信息');
            setDialogData(null); // 空表单，用于添加新活动
            setDialogFields(activityAddFields); // 使用活动新增字段
            setDialogOpen(true);
        } else if (section === '实习') {
            setCurrentSection('实习信息');
            setDialogTitle('添加实习信息');
            setDialogData(null); // 空表单，用于添加新实习
            setDialogFields(internshipAddFields); // 使用实习新增字段
            setDialogOpen(true);
        } else if (section === '工作') {
            // 打开工作信息添加对话框
            setAddWorkExperienceOpen(true);
        } else if (section === '日常') {
            setCurrentSection('CDC记录');
            setDialogTitle('添加CDC记录');
            setDialogData(null); // 空表单，用于添加新CDC记录
            setDialogFields(getDailyInfoAddFields(recordTypeOptions)); // 使用CDC记录新增字段
            setDialogOpen(true);
        } else {
            // 其他类型的添加功能可以同样实现
            console.log(`${section}的添加功能尚未实现`);
        }
    };

    // 查看详情处理函数
    const handleView = async (section: string, id: number) => {
        console.log(`查看${section}详情，ID: ${id}`);

        if (section === '活动') {
            // 查找对应ID的活动
            const activity = activities.find((item) => item.id === id);
            if (activity) {
                setSelectedActivity(activity);
                setActivityDetailOpen(true);
            } else {
                setSnackbarMessage('未找到活动信息');
                setSnackbarSeverity('error');
                setSnackbarOpen(true);
            }
        } else if (section === '实习') {
            // 查找对应ID的实习
            const internship = internships.find((item) => item.id === id);
            if (internship) {
                setSelectedInternship(internship);
                setInternshipDetailOpen(true);
            } else {
                setSnackbarMessage('未找到实习信息');
                setSnackbarSeverity('error');
                setSnackbarOpen(true);
            }
        } else if (section === '工作') {
            // 查找对应ID的工作信息
            const workExp = workExperience.find((item) => item.id === id);
            if (workExp) {
                // 设置加载状态
                setWorkExperienceLoading(true);
                setWorkExperienceError(null);

                try {
                    // 获取工作信息详情
                    const detailResponse = await getStudentOfferDetail({
                        record_id: record_id || '',
                        sid: sid || '',
                        offer_info_id: id.toString()
                    });

                    // 将详细信息合并到工作信息对象中
                    const detailedWorkExp = {
                        ...workExp,
                        collegeName: detailResponse.college_name,
                        projectName: detailResponse.project_name,
                        projectType: detailResponse.project_type,
                        position: detailResponse.position,
                        salaryMonth: detailResponse.salary_month,
                        salaryYear: detailResponse.salary_year,
                        entranceDate: detailResponse.entrance_date,
                        entranceYear: detailResponse.entrance_year,
                        remark: detailResponse.remark
                    };

                    // 设置选中的工作信息并打开详情对话框
                    setSelectedWorkExperience(detailedWorkExp);
                    setWorkExperienceDetailOpen(true);
                } catch (error) {
                    console.error('获取工作信息详情失败:', error);
                    setWorkExperienceError('获取工作信息详情失败，请稍后重试');
                    setSnackbarMessage('获取工作信息详情失败，请稍后重试');
                    setSnackbarSeverity('error');
                    setSnackbarOpen(true);
                } finally {
                    setWorkExperienceLoading(false);
                }
            } else {
                setSnackbarMessage('未找到工作信息');
                setSnackbarSeverity('error');
                setSnackbarOpen(true);
            }
        }
        // 其他类型的详情查看可以同样实现
    };

    // 编辑具体活动
    const handleEditActivity = (activity: Activity) => {
        setCurrentSection('活动信息');
        setDialogTitle('编辑活动信息');

        // 如果活动时间是时间戳格式，需要转换为日期字符串
        let formattedActivity = { ...activity };

        if (activity.date && !isNaN(Number(activity.date))) {
            // 假设时间戳是秒级的
            const timestamp = Number(activity.date) * 1000;
            const date = new Date(timestamp);
            // 格式化为 YYYY-MM-DD 格式，适用于日期选择器
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            formattedActivity.date = `${year}-${month}-${day}`;
        }

        setDialogData(formattedActivity);
        setDialogFields(activityEditFields); // 使用活动编辑字段
        setDialogOpen(true);
    };

    // 编辑具体实习
    const handleEditInternship = (internship: Internship) => {
        setCurrentSection('实习信息');
        setDialogTitle('编辑实习信息');

        // 如果实习时间是时间戳格式，需要转换为日期字符串
        let formattedInternship = { ...internship };

        // 处理开始时间
        if (internship.startDate && !isNaN(Number(internship.startDate))) {
            // 假设时间戳是秒级的
            const timestamp = Number(internship.startDate) * 1000;
            const date = new Date(timestamp);
            // 格式化为 YYYY-MM-DD 格式，适用于日期选择器
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            formattedInternship.startDate = `${year}-${month}-${day}`;
        }

        // 处理结束时间
        if (internship.endDate && !isNaN(Number(internship.endDate))) {
            // 假设时间戳是秒级的
            const timestamp = Number(internship.endDate) * 1000;
            const date = new Date(timestamp);
            // 格式化为 YYYY-MM-DD 格式，适用于日期选择器
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            formattedInternship.endDate = `${year}-${month}-${day}`;
        }

        setDialogData(formattedInternship);
        setDialogFields(internshipEditFields); // 使用实习编辑字段
        setDialogOpen(true);
    };

    // 编辑具体Offer信息
    const handleEditWorkExperience = (workExp: WorkExperience) => {
        setCurrentSection('Offer信息');
        setDialogTitle('编辑Offer信息');

        // 创建一个新的对象，不修改原始对象
        let formattedWorkExp = { ...workExp };

        // 将acceptStatus映射到offerStatus，以便在编辑表单中正确显示
        const formattedWorkExpWithOfferStatus = {
            ...formattedWorkExp,
            offerStatus: workExp.acceptStatus
        };

        // 设置当前的offer类型，用于后续更新字段列表
        setCurrentOfferType(workExp.offerType);

        // 根据offer类型获取不同的字段列表
        setDialogData(formattedWorkExpWithOfferStatus);
        setDialogFields(getWorkExperienceEditFields(offerTypeOptions, offerStatusOptions, workExp.offerType)); // 传递offer类型
        setDialogOpen(true);
    };

    // 关闭活动详情对话框
    const handleCloseActivityDetail = () => {
        setActivityDetailOpen(false);
        setSelectedActivity(null);
    };

    // 关闭实习详情对话框
    const handleCloseInternshipDetail = () => {
        setInternshipDetailOpen(false);
        setSelectedInternship(null);
    };

    // 关闭工作信息详情对话框
    const handleCloseWorkExperienceDetail = () => {
        setWorkExperienceDetailOpen(false);
        setSelectedWorkExperience(null);
    };

    // 删除处理函数
    const handleDelete = (section: string, id: number) => {
        console.log(`删除${section}信息，ID: ${id}`);

        if (section === '活动') {
            // 设置要删除的活动ID
            setDeleteActivityId(id);

            // 设置确认对话框内容
            setConfirmDialogTitle('删除活动');
            setConfirmDialogContent('确定要删除这条活动信息吗？此操作不可恢复。');

            // 设置确认操作，将删除操作包装在一个函数中，等待用户确认后再执行
            setConfirmDialogAction(() => async () => {
                await deleteActivity(id);
            });

            // 打开确认对话框
            setConfirmDialogOpen(true);
        } else if (section === '实习') {
            // 设置确认对话框内容
            setConfirmDialogTitle('删除实习');
            setConfirmDialogContent('确定要删除这条实习信息吗？此操作不可恢复。');

            // 设置确认操作，将删除操作包装在一个函数中，等待用户确认后再执行
            setConfirmDialogAction(() => async () => {
                await deleteInternship(id);
            });

            // 打开确认对话框
            setConfirmDialogOpen(true);
        } else if (section === '工作') {
            // 设置确认对话框内容
            setConfirmDialogTitle('删除工作信息');
            setConfirmDialogContent('确定要删除这条工作信息吗？此操作不可恢复。');

            // 设置确认操作，将删除操作包装在一个函数中，等待用户确认后再执行
            setConfirmDialogAction(() => async () => {
                await deleteWorkExperience(id);
            });

            // 打开确认对话框
            setConfirmDialogOpen(true);
        } else {
            // 其他类型的删除功能可以同样实现
            console.log(`${section}的删除功能尚未实现`);
        }
    };

    // 删除活动的具体实现
    const deleteActivity = async (id: number) => {
        try {
            setActivitiesLoading(true);
            setActivitiesError(null);

            // 查找对应ID的活动
            const activity = activities.find((item) => item.id === id);

            if (!activity) {
                throw new Error('未找到要删除的活动信息');
            }

            // 准备请求参数
            const params: DeleteStudentActivityInfoParams = {
                sid: sid || '',
                record_id: record_id || '',
                activity_info_id: id.toString()
            };

            // 调用删除接口
            await deleteStudentActivityInfo(params);

            // 删除成功后重新获取活动列表
            await fetchActivityInfo();

            // 显示成功提示
            setSnackbarMessage('活动信息删除成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('删除活动信息失败:', error);
            setActivitiesError('删除活动信息失败，请稍后重试');
            setSnackbarMessage('删除活动信息失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setActivitiesLoading(false);
            // 重置删除状态
            setDeleteActivityId(null);
        }
    };

    // 删除实习的具体实现
    const deleteInternship = async (id: number) => {
        try {
            setInternshipsLoading(true);
            setInternshipsError(null);

            // 查找对应ID的实习
            const internship = internships.find((item) => item.id === id);

            if (!internship) {
                throw new Error('未找到要删除的实习信息');
            }

            // 准备请求参数
            const params: DeleteStudentInternshipInfoParams = {
                sid: sid || '',
                record_id: record_id || '',
                internship_info_id: id.toString()
            };

            // 调用删除接口
            await deleteStudentInternshipInfo(params);

            // 删除成功后重新获取实习列表
            await fetchInternshipInfo();

            // 显示成功提示
            setSnackbarMessage('实习信息删除成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('删除实习信息失败:', error);
            setInternshipsError('删除实习信息失败，请稍后重试');
            setSnackbarMessage('删除实习信息失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setInternshipsLoading(false);
        }
    };

    // 删除工作信息的具体实现
    const deleteWorkExperience = async (id: number) => {
        try {
            setWorkExperienceLoading(true);
            setWorkExperienceError(null);

            // 查找对应ID的工作信息
            const workExp = workExperience.find((item) => item.id === id);

            if (!workExp) {
                throw new Error('未找到要删除的工作信息');
            }

            // 准备请求参数
            const params: DeleteStudentOfferInfoParams = {
                sid: sid || '',
                record_id: record_id || '',
                offer_info_id: id.toString()
            };

            // 调用删除接口
            await deleteStudentOfferInfo(params);

            // 删除成功后重新获取工作信息列表
            await fetchOfferInfo();

            // 显示成功提示
            setSnackbarMessage('工作信息删除成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('删除工作信息失败:', error);
            setWorkExperienceError('删除工作信息失败，请稍后重试');
            setSnackbarMessage('删除工作信息失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setWorkExperienceLoading(false);
        }
    };

    // 处理确认对话框的确认操作
    const handleConfirmDialogConfirm = async () => {
        try {
            // 执行确认操作
            // confirmDialogAction 现在返回一个函数，需要先调用它来获取实际的操作函数
            const action = confirmDialogAction();
            if (action) {
                await action();
            }
        } catch (error) {
            console.error('确认操作执行失败:', error);
        } finally {
            // 关闭确认对话框
            setConfirmDialogOpen(false);
        }
    };

    // 处理确认对话框的取消操作
    const handleConfirmDialogCancel = () => {
        // 重置删除状态
        setDeleteActivityId(null);
        // 关闭确认对话框
        setConfirmDialogOpen(false);
    };

    // 关闭工作信息添加对话框
    const handleCloseAddWorkExperience = () => {
        setAddWorkExperienceOpen(false);
    };

    // 处理工作信息添加
    const handleAddWorkExperience = async (params: any) => {
        try {
            setWorkExperienceLoading(true);
            setWorkExperienceError(null);

            // 调用创建工作信息的API
            await createStudentOfferInfo(params);

            // 创建成功后重新获取工作信息列表
            await fetchOfferInfo();

            // 显示成功提示
            setSnackbarMessage('工作信息添加成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);

            // 关闭添加对话框
            setAddWorkExperienceOpen(false);
        } catch (error) {
            console.error('添加工作信息失败:', error);
            setWorkExperienceError('添加工作信息失败，请稍后重试');
            setSnackbarMessage('添加工作信息失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setWorkExperienceLoading(false);
        }
    };

    // 编辑CDC记录处理函数
    const handleEditDailyInfo = (log: Log) => {
        setCurrentSection('CDC记录');
        setDialogTitle('编辑CDC记录');

        // 将时间格式化为 YYYY-MM-DD，用于日期选择器
        let formattedTime = log.time;
        if (formattedTime) {
            try {
                // 使用dayjs处理日期
                const date = dayjs(formattedTime);
                if (date.isValid()) {
                    formattedTime = date.format('YYYY-MM-DD');
                }
            } catch (error) {
                console.error('日期格式化失败:', error);
            }
        }

        // 将Log对象转换为编辑表单所需的格式
        const formattedData = {
            daily_info_id: log.id,
            record_name: log.recordOwner,
            record_type: log.recordType,
            record_time: formattedTime,
            record_detail: log.content
        };

        setDialogData(formattedData);
        setDialogFields(getDailyInfoEditFields(recordTypeOptions));
        setDialogOpen(true);
    };

    // 删除CDC记录处理函数
    const handleDeleteDailyInfo = (id: number) => {
        // 设置确认对话框内容
        setConfirmDialogTitle('删除CDC记录');
        setConfirmDialogContent('确定要删除这条CDC记录吗？此操作不可恢复。');

        // 设置确认操作
        setConfirmDialogAction(() => async () => {
            await performDeleteDailyInfo(id);
        });

        // 打开确认对话框
        setConfirmDialogOpen(true);
    };

    // 执行删除CDC记录的操作
    const performDeleteDailyInfo = async (id: number) => {
        try {
            // 设置加载状态
            setDailyInfoLoading(true);
            setDailyInfoError(null);

            // 找到要删除的CDC记录
            const dailyInfoToDelete = dailyInfo.find((item) => item.id === id);

            if (!dailyInfoToDelete) {
                throw new Error('找不到要删除的CDC记录');
            }

            // 准备请求参数
            const params: DeleteStudentDailyInfoParams = {
                record_id: record_id || '',
                sid: sid || '',
                daily_info_id: dailyInfoToDelete.id.toString()
            };

            // 调用删除接口
            await deleteStudentDailyInfo(params);

            // 删除成功后重新获取CDC记录
            await fetchDailyInfo();

            // 显示成功提示
            setSnackbarMessage('CDC记录删除成功');
            setSnackbarSeverity('success');
            setSnackbarOpen(true);
        } catch (error) {
            console.error('删除CDC记录失败:', error);
            setDailyInfoError('删除CDC记录失败，请稍后重试');
            setSnackbarMessage('删除CDC记录失败，请稍后重试');
            setSnackbarSeverity('error');
            setSnackbarOpen(true);
        } finally {
            setDailyInfoLoading(false);
        }
    };

    // 处理分页变化
    const handlePageChange = (_event: unknown, newPage: number, type: string) => {
        setPage(newPage);

        switch (type) {
            case 'activities':
                fetchActivityInfo(newPage.toString());
                break;
            case 'internships':
                fetchInternshipInfo(newPage.toString());
                break;
            case 'workExperience':
                fetchOfferInfo(newPage.toString());
                break;
            case 'dailyInfo':
                fetchDailyInfo(newPage.toString());
                break;
            default:
                break;
        }
    };

    // 处理Offer类型变化
    const handleOfferTypeChange = (offerType: string, formData: Record<string, any>) => {
        // 更新当前的offer类型
        setCurrentOfferType(offerType);

        // 更新对话框数据，确保offerType值被正确更新
        setDialogData(formData);

        // 根据新的offer类型更新字段列表
        setDialogFields(getWorkExperienceEditFields(offerTypeOptions, offerStatusOptions, offerType));
    };

    // 关闭对话框处理函数
    const handleCloseDialog = () => {
        setDialogOpen(false);
        setDialogData(null);
        setDialogFields([]);
        setCurrentSection('');
        setCurrentOfferType('');
    };

    return (
        <Box className="detail-page">
            {/* 面包屑导航 */}
            <Box className="page-header">
                <Breadcrumb items={breadcrumbItems} />
            </Box>

            {/* 隐藏的文件输入框 - 基础信息 */}
            <input
                type="file"
                ref={baseInfoFileInputRef}
                onChange={handleBaseInfoFileChange}
                accept=".xlsx"
                style={{ display: 'none' }}
            />

            {/* 隐藏的文件输入框 - 活动信息 */}
            <input
                type="file"
                ref={activityFileInputRef}
                onChange={handleActivityFileChange}
                accept=".xlsx"
                style={{ display: 'none' }}
            />

            {/* 隐藏的文件输入框 - 实习信息 */}
            <input
                type="file"
                ref={internshipFileInputRef}
                onChange={handleInternshipFileChange}
                accept=".xlsx"
                style={{ display: 'none' }}
            />

            {/* 基础信息 */}
            <BasicInfoSection
                basicInfo={basicInfo}
                loading={loading}
                error={error}
                onEdit={() => handleEdit('基础信息')}
                onImport={handleImportBaseInfo}
            />

            {/* 背景信息 */}
            <BackgroundInfoSection
                backgroundInfo={backgroundInfo}
                loading={backgroundLoading}
                error={backgroundError}
                onEdit={() => handleEdit('背景信息')}
            />

            {/* 活动信息 */}
            <ActivitiesSection
                activities={activities}
                onEdit={handleEditActivity}
                onAdd={() => handleAdd('活动')}
                onImport={handleImportActivityInfo}
                onView={(id) => handleView('活动', id)}
                onDelete={(id) => handleDelete('活动', id)}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={(_event, newPage) => handlePageChange(_event, newPage, 'activities')}
                loading={activitiesLoading}
                error={activitiesError}
                total={activitiesTotal}
            />

            {/* 实习信息 */}
            <InternshipsSection
                internships={internships}
                onEdit={handleEditInternship}
                onAdd={() => handleAdd('实习')}
                onImport={handleImportInternshipInfo}
                onView={(id) => handleView('实习', id)}
                onDelete={(id) => handleDelete('实习', id)}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={(_event, newPage) => handlePageChange(_event, newPage, 'internships')}
                loading={internshipsLoading}
                error={internshipsError}
                total={internshipsTotal}
            />

            {/* 工作信息 */}
            <WorkExperienceSection
                workExperience={workExperience}
                onEdit={handleEditWorkExperience}
                onAdd={() => handleAdd('工作')}
                onView={(id) => handleView('工作', id)}
                onDelete={(id) => handleDelete('工作', id)}
                // onDownload={handleDownload}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={(_event, newPage) => handlePageChange(_event, newPage, 'workExperience')}
                loading={workExperienceLoading}
                error={workExperienceError}
                total={workExperienceTotal}
            />

            {/* 关键信息（包含毕业信息） */}
            <KeyInfoSection
                keyInfo={keyInfo}
                graduationInfo={graduationInfo}
                onEdit={() => handleEdit('关键信息')}
                onEditGraduation={() => handleEdit('毕业信息')}
                loading={keyInfoLoading}
                error={keyInfoError}
                graduationLoading={graduationInfoLoading}
                graduationError={graduationInfoError}
            />

            {/* CDC记录 */}
            <DailyInfoSection
                dailyInfo={dailyInfo}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={(_event, newPage) => handlePageChange(_event, newPage, 'dailyInfo')}
                onAdd={() => handleAdd('日常')}
                onEdit={(log) => handleEditDailyInfo(log)}
                onDelete={(id) => handleDeleteDailyInfo(id)}
                loading={dailyInfoLoading}
                error={dailyInfoError}
                total={dailyInfoTotal}
            />

            {/* 通用编辑对话框 */}
            <EditDialog
                open={dialogOpen}
                onClose={handleCloseDialog}
                title={dialogTitle}
                data={dialogData}
                fields={dialogFields}
                onSave={handleSaveData}
                onOfferTypeChange={currentSection === 'Offer信息' ? handleOfferTypeChange : undefined}
            />

            {/* 提示消息 */}
            <Snackbar
                open={snackbarOpen}
                autoHideDuration={6000}
                onClose={handleSnackbarClose}
                anchorOrigin={{ vertical: 'top', horizontal: 'center' }}>
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>

            {/* 活动详情对话框 */}
            <ActivityDetailDialog
                open={activityDetailOpen}
                onClose={handleCloseActivityDetail}
                activity={selectedActivity}
            />

            {/* 实习详情对话框 */}
            <InternshipDetailDialog
                open={internshipDetailOpen}
                onClose={handleCloseInternshipDetail}
                internship={selectedInternship}
                onEdit={() => {
                    if (selectedInternship) {
                        handleCloseInternshipDetail();
                        handleEditInternship(selectedInternship);
                    }
                }}
            />

            {/* 工作信息详情对话框 */}
            <WorkExperienceDetailDialog
                open={workExperienceDetailOpen}
                onClose={handleCloseWorkExperienceDetail}
                workExperience={selectedWorkExperience}
                onEdit={() => {
                    if (selectedWorkExperience) {
                        handleCloseWorkExperienceDetail();
                        handleEditWorkExperience(selectedWorkExperience);
                    }
                }}
            />

            {/* 确认对话框 */}
            <ConfirmDialog
                open={confirmDialogOpen}
                title={confirmDialogTitle}
                content={confirmDialogContent}
                onConfirm={handleConfirmDialogConfirm}
                onCancel={handleConfirmDialogCancel}
            />

            {/* 工作信息添加对话框 */}
            <AddWorkExperienceDialog
                open={addWorkExperienceOpen}
                onClose={handleCloseAddWorkExperience}
                onAdd={handleAddWorkExperience}
                sid={sid || ''}
                record_id={record_id || ''}
            />
        </Box>
    );
};

export default StudentDetail;
